#import "BWBackStitchEditingTool.h"

#import "BWBackStitchStorage.h"
#import "BWBackStitchLayer.h"

@implementation BWBackStitchEditingTool

- (void) unselectStitch
{
    if (draggingStitch != nil) {
        [draggingLayer selectStitch: nil];
        draggingLayer = nil;
        draggingStitch = nil;
    }

} // unslectStitch


- (void) dealloc
{
    [self unselectStitch];
    [super dealloc];

} // dealloc


- (BOOL) handleMouseDown: (NSEvent *) event
                 atPoint: (NSPoint) mouse
{
    [self unselectStitch];

    dragged = NO;
    draggingLayer = nil;

    NSArray *affectedLayers = [self affectedLayers];

    NSEnumerator *enumerator = [affectedLayers objectEnumerator];

    BWBackStitchLayer *candidate;
    while (candidate = [enumerator nextObject]) {

        BWBackStitch *stitch;
        BWBackStitch_Part part;

        stitch = [candidate stitchUnderPoint: mouse
                            part: &part];

        if (stitch != nil) {
            
            draggingLayer = candidate;
            [draggingLayer selectStitch: stitch];
            
            draggingStitch = stitch;
            draggingPart = part;
            break;
        }
    }

    return (YES);

} // handleMouseDown


- (void) handleMouseDragged: (NSEvent *) event
                    atPoint: (NSPoint) mouse
{
    if (draggingStitch) {
        int row, column;
        BWGrid_Quadrant quadrant;
        
        [geometry getIntersectionRow: &row
                  column: &column
                  quadrant: &quadrant
                  nearPoint: mouse];

        [draggingLayer setOverrideForPart: draggingPart
               toRow: row
               column: column
               quadrant: quadrant];

        dragged = YES;
    }

} // handleMouseDragged


- (void) handleMouseUp: (NSEvent *) event
               atPoint: (NSPoint) mouse
{
    if (dragged && draggingStitch) {
        [draggingLayer commitOverride];
    }
    // otherwise leave it selecte

} // handleMouseUp


- (void) handleKeyDown: (NSEvent *) event
               atPoint: (NSPoint) mouse
{
    NSString *chars = [event characters];
    unichar character = [chars characterAtIndex: 0];

    if (character == 27) {
        // abort the drag
        [self unselectStitch];
    }
  
    if (character == NSDeleteCharacter) {
        [draggingLayer removeSelection];
        [draggingLayer selectStitch: nil];
        [self unselectStitch];
    }

} // handleKeyDown



- (NSArray *) affectedLayers
{
    return ([self allLayersForKind: kLayerKind_BackStitch]);

} // affectedLayers


- (NSString *) name
{
    return (@"Edit backstitches");
} // name


@end // BWBackStitchEditingTool

